home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: Pointer to Functions and Calls thereof??
- Date: 17 Apr 1996 15:53:54 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4l346i$iph@sparcserver.lrz-muenchen.de>
- References: <Dq01Ft.Dqn@latcs1.lat.oz.au>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- woelkerl@lion.cs.latrobe.edu.au (Eric Woelkerling) writes:
-
- > Hi! Can anybody fill me in as to how to get a pointer to a function
- >and then use this to do the call?? I have a situation where a particular function
- >will be selected from a set of functions and used throughout my entire code,
- >but the function selected will depend on the runtime selection by thge user..
-
- >so far.. I have got as far as..
-
- > void func1(void){naughty bits}
- > void func2(void){naughty bits}
-
- > void main(void)
-
- I will not comment on this!
-
- > { void *a[1];
-
- There is some use for arrays of size 1, e.g. for "simulating" call
- by reference in a "user friendly" way, but storing _two_ pointers
- to anything is _not_ a good use for an array of 1 void pointer.
-
- > a[1]=func1;
-
- A void pointer can hold all data pointers, but this does not include
- pointers to functions. So why do you insist on using void pointers
- to store pointers to functions?
-
- The only element of "a" that can be accessed given the current
- definition of "a" is "a[0]".
-
- > a[2]=func2;
-
- If you want to access "a[2]", define "a" as "T a[3]". Arrays are
- zero based in C.
-
- > (*a[1])();
-
- "a" is an array of pointers to void. "a[1]" is a pointer to void,
- and dereferencing it is therefore not possible. If a void pointer
- can hold a pointer to a function in your environment, something
- like
-
- ((void (*)(void))a[1])();
-
- will work. If you prefer "dereferencing" function pointers when
- you call them, this will become
-
- (*((void (*)(void))a[1]))();
-
- but remember, both are not portable to machines where void pointers
- cannot hold pointers to functions (and PCs using the right memory
- model are such machines). Why don't you simply define a "proper"
- function pointer type, as in
-
- typedef void (*PROC)(void);
-
- declare "a" as an array of PROC, as in
-
- PROC a[2];
-
- and use it in a "simple" way, as in
-
- a[1]();
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
-
-